﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Maxleaf.EDI.API.Contract.Client.Commands;
using Maxleaf.EDI.Domain;
using Maxleaf.EDI.Domain.EDI;

namespace Maxleaf.EDI.Core.Handlers.CommandHandlers
{
    public class ResetCurrentUserPasswordCommandHandler : ICommandHandler<ResetPasswordCommand>
    {
        private readonly IUnitOfWorkProvider unitOfWorkProvider;

        private readonly IRepository<User_DB> userRepository;

        public ResetCurrentUserPasswordCommandHandler(
            IRepository<User_DB> userRepository,
            IUnitOfWorkProvider unitOfWorkProvider)
        {
            this.userRepository = userRepository;
            this.unitOfWorkProvider = unitOfWorkProvider;
        }

        public void Handle(ResetPasswordCommand command)
        {
            using (var unitOfWork = this.unitOfWorkProvider.GetEDIUnitOfWork())
            {
                var user = this.userRepository.GetSingleOrDefault(unitOfWork, u => u.UserName == command.UserName);
                if (!user.Password.Equals(command.OldHashPassword,StringComparison.InvariantCultureIgnoreCase))
                { 
                    throw new Exception("Wrong Old Password");
                }

                user.Password = command.NewHashPassword;

                this.userRepository.Update(unitOfWork,user);
               
                unitOfWork.Commit();
            }
        }
    }
}
